package com.hz.house.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.hz.house.enums.ResultCodeEnum;
import com.hz.house.token.CurrentUser;
import com.hz.house.token.JWTUtil;
import com.hz.house.token.UaaClaims;

import lombok.extern.slf4j.Slf4j;

/**
 * JWTtoken的拦截
 * @author lfw
 *
 */
@Order(1)
@Component
@Slf4j
public class TokenInterceptor extends OncePerRequestFilter{

	@Autowired
	private JWTUtil jwtUtil;
	
	
	private static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
	
	/**只会拦截api相关的接口*/
	private static String INTERCEPT_EXP= "/**/api/**";
	
	private static PathMatcher matcher = new AntPathMatcher();
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		 
		String url = request.getServletPath();
		if(!matcher.match(INTERCEPT_EXP, url)) {
			filterChain.doFilter(request, response);
			return;
		}
		String token = request.getHeader("Authorization");
		if(StringUtils.isEmpty(token)) {
			logger.error("token为空");
			print(new ResultBean(ResultCodeEnum.UNAUTHORIZED.code(), "未授权", null), response);
			return;
		}
		UaaClaims res = jwtUtil.validate(token);
		if(res==null) {
			logger.error("token校验失败");
			print(new ResultBean(ResultCodeEnum.UNAUTHORIZED.code(), "未授权", null), response);
			return;
		}
		log.info("访问接口:"+url+",userid:"+res.getUserId());
		CurrentUser.setCurrentUserId(Integer.parseInt(res.getUserId()));
		filterChain.doFilter(request, response);
		CurrentUser.clearCurrentUserId();
		
	}

	 
	private void print(ResultBean result,HttpServletResponse rep) {
		
		rep.setCharacterEncoding("UTF-8");
		rep.setContentType("text/html; charset=utf-8");
		String json = JSON.toJSONString(result);
		PrintWriter writer=null;
		try {
			writer = rep.getWriter();
			writer.print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(writer != null)
				writer.close();
		}
		
	}
	
	
}
